package com.crpc.core.serialize.impl;


import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.serialize.Serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wzy
 * @version 1.0
 * @description:
 * @date 2023/9/29 15:54
 */
@Slf4j
public class JSONSerializer implements Serializer {
    public JSONSerializer() {
    }

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        try {
            log.info("===============Json序列化方式(JackSon)===============");
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsBytes(object);
        } catch (Exception e) {
            log.error("Json(JackSon)序列化对象：{}，失败原因：{}", object, e.getMessage());
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.Serialize_ERROR);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || clazz == null) {
            return null;
        }
        try {
            log.info("===============Json反序列化方式(JackSon)===============");
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(bytes, clazz);
        } catch (Exception e) {
            log.error("Json(JackSon)反序列化对象：{}，失败原因：{}", bytes, e.getMessage());
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.Serialize_ERROR);
        }
    }
}
